package libs

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"sync"
)

type CustomUser struct {
	Name string `json:"name" binding:"required,no_repeat"`
}

var (
	logined       = []string{}
	logined_mutex sync.Mutex
)

func no_repeat_validator(fl validator.FieldLevel) bool {
	user := fl.Parent().Interface().(CustomUser)

	for _, name := range logined {
		if name == user.Name {
			fmt.Println("一样的!")
			return false
		}
	}

	return true

}

func CustomValidate(context *gin.Context) {
	validator, okay := binding.Validator.Engine().(*validator.Validate)

	if okay {
		err := validator.RegisterValidation("no_repeat", no_repeat_validator)
		if err != nil {
			context.String(200, "失败!")
			return
		}
		var customUser CustomUser
		err = context.ShouldBindJSON(&customUser)
		if err != nil {
			context.String(201, "不能重复请求!!")
			return
		}
		context.String(200, "成功")
		logined_mutex.Lock()
		logined = append(logined, customUser.Name)
		defer logined_mutex.Unlock()

	} else {
		context.String(201, "失败")
	}
}
